import React from 'react'
import Taro from '@tarojs/taro'
import { Tabbar } from '@nutui/nutui-react-taro';

import Icon from "@/components/icon"
import { EnumTabBar } from "@/constants";

const { height, color, selectedColor, list } = EnumTabBar;

const TabBarNutui: React.FC = () => {
  const currentPath = Taro.getCurrentInstance().router?.path ?? list[0].pagePath;
  const selectedIdx = list.findIndex((item) => isEqualPath(item.pagePath, currentPath))

  return <Tabbar
    fixed
    value={selectedIdx}
    inactiveColor={color}
    activeColor={selectedColor}
    onSwitch={(idx) => Taro.switchTab({url: list[idx].pagePath})}
    style={{
      height,
    }}
  >
    {list.map((item, index) => {
      const selected = selectedIdx === index;
      return <Tabbar.Item
        key={item.pagePath}
        title={item.text}
        icon={<Icon
          // @ts-ignore
          name={item.iconName}
          size={38}
          style={{color: selected ? selectedColor : color}}
        />}
      />
    })}
  </Tabbar>
}

export default TabBarNutui;

const isEqualPath = (a: string, b: string) => (a || '').replace(/^\//, '') === (b || '').replace(/^\//, '')
